import axios from 'axios'
import qs from 'qs'

const SERVER = 'https://api.huhuiyu.top'

const tokenkey = SERVER + '_tokenkey';

const tokeninfo = {
  load: () => {
    let token = localStorage.getItem(tokenkey);
    return token ? token : '';
  },
  save: (data) => {
    // 如果应答信息中存在token就保存到本地储存
    if (data && data.token) {
      localStorage.setItem(tokenkey, data.token);
    }
  },
  clear: () => {
    localStorage.removeItem(tokenkey);
  },
};

const api = {
  uploadUserLogo: (file, cb) => {
    // 上传文件必须使用FormData
    const formdata = new FormData();
    formdata.append('file', file);
    const url = SERVER + '/user/logo';
    const promise = axios({
      url: url,
      method: 'POST',
      data: formdata,
      headers: {
        // 通过头信息传递token认证信息
        Authorization: tokeninfo.load(),
        // 上传文件的指定类型
        'Content-Type': 'multipart/form-data',
      },
    })

    promise
      .then((resp) => {
        console.log('应答结果：', resp);
        // 保存token信息
        tokeninfo.save(resp.data)
        cb(resp.data);
      })
      .catch((err) => {
        console.log('请求出错：', err);
        cb({ success: false, message: '出bug,赶紧叫老师打你一顿' });
      });

  },







  userlogo: id => {
    return `${SERVER}/user/logo/${id}?ts=${new Date().getTime()}`
  },
  test: () => {
    console.log('测试信息：', axios, qs)
  },

  send: (url, params, method, cb) => {
    // 请求的方式替换成大写
    method = method ? method.toUpperCase() : 'GET';
    // 完整的url
    url = SERVER + url;
    // get请求需要转换参数为查询字符串并拼接到url
    if (method == 'GET') {
      url += '?' + qs.stringify(params);
      params = '';
    }
    // 通过axios发送请求
    let promise = axios({
      url: url,
      method: method,
      data: params,
      headers: {
        // 通过头信息传递token认证信息
        Authorization: tokeninfo.load(),
      },
    });

    promise
      .then((resp) => {
        console.log('应答结果：', resp);
        // 保存token信息
        tokeninfo.save(resp.data)
        cb(resp.data);
      })
      .catch((err) => {
        console.log('请求出错：', err);
        cb({ success: false, message: '出bug,赶紧叫老师打你一顿' });
      });

  },

  // get请求
  get: (url, params, cb) => {
    api.send(url, params, 'get', cb);
  },
  // post请求
  post: (url, params, cb) => {
    api.send(url, params, 'post', cb);
  },
  // delete请求
  delete: (url, params, cb) => {
    api.send(url, params, 'delete', cb);
  },
  // put请求
  put: (url, params, cb) => {
    api.send(url, params, 'put', cb);
  },
  // patch请求
  patch: (url, params, cb) => {
    api.send(url, params, 'patch', cb);
  },






}

export { api as default, api as api }